package com.polaris.live.adapter

import android.view.View
import androidx.lifecycle.LifecycleCoroutineScope
import com.bumptech.glide.Glide
import com.polaris.live.common.adapter.BaseBindingAdapter
import com.polaris.live.common.adapter.VBViewHolder
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.databinding.AdapterHonorWallBinding
import com.polaris.live.resp.back_resp.UserMedalVo
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.playAsync
import kotlinx.coroutines.launch
import java.io.File

/**
 * HonorWallAdapter
 *
 * @author Created by 半仙 on 2024/4/20/020 16:33
 */
class HonorWallAdapter(
    private val lifecycleScope: LifecycleCoroutineScope,
) : BaseBindingAdapter<AdapterHonorWallBinding, UserMedalVo>() {

    override fun convert(holder: VBViewHolder<AdapterHonorWallBinding>, item: UserMedalVo) {
        holder.vb.apply {
            ivHonorItem.visibility = View.GONE
            pagHonorItem.visibility = View.GONE
            if (item.createTime != null) {
                llItemCenter.alpha = 1f
                if (item.pagUrl?.isNotEmpty() == true) {
                    //这里的逻辑 如果没有下载完 先展示灰色的图  等下载完在展示
                    val path = FileUtils.getFilePath(FileUtils.getPagFile(), item.pagUrl)
                    if (File(path).exists()) {
                        pagHonorItem.visibility = View.VISIBLE
                        pagHonorItem.playAsync(lifecycleScope, item.pagUrl) { pagFile ->
                            val layers = item.layers
                            if (layers != null) {
                                try {
                                    lifecycleScope.launch(CoroutineScopeManager.ioDispatcher) {
                                        CommonUtils.pagReplace(context, pagFile, layers)
                                    }
                                } catch (_: Exception) {
                                }
                            }
                        }
                    } else {
                        showImage(holder, item)
                    }
                } else {
                    ivHonorItem.visibility = View.VISIBLE
                    Glide.with(context).load(ImageUtils.imgPath(item.photoUrl)).into(ivHonorItem)
                }
            } else {
                showImage(holder, item)
            }
            tvHonorItem.text = item.name
        }
    }

    private fun showImage(holder: VBViewHolder<AdapterHonorWallBinding>, item: UserMedalVo) {
        holder.vb.apply {
            ivHonorItem.visibility = View.VISIBLE
            llItemCenter.alpha = 0.4f
            Glide.with(context).load(ImageUtils.imgPath(item.photoUrl))
                .into(ivHonorItem)
        }
    }

}